﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Runtime.InteropServices;

namespace SFP.Input
{
    public abstract class Mouse
    {
        internal static SFPForm form;

        private static bool LButtonClicked = false;
        private static bool RButtonClicked = false;
        private static bool MButtonClicked = false;

        internal static void HandleMouseDown(object sender, MouseEventArgs e)
        {
            setMouseButton(e.Button, true);
        }

        internal static void HandleMouseUp(object sender, MouseEventArgs e)
        {
            setMouseButton(e.Button, false);
        }

        internal static void setMouseButton(MouseButtons button, bool state)
        {
            switch (button)
            {
                case MouseButtons.Left:
                    LButtonClicked = state;
                    break;
                case MouseButtons.Right:
                    RButtonClicked = state;
                    break;
                case MouseButtons.Middle:
                    MButtonClicked = state;
                    break;
            }
        }

        public static bool isLButtonClicked()
        {
            return LButtonClicked;
        }

        public static bool isRButtonClicked()
        {
            return RButtonClicked;
        }

        public static bool isMButtonClicked()
        {
            return MButtonClicked;
        }

        public static Point getCurrentLocation()
        {
            Point mouseLoc = Cursor.Position;
            Point formLoc = form.Location;
            Point frameLoc = new Point((form.getPictureBox().Width - form.getPictureBox().Image.Width) / 2,
                                       (form.getPictureBox().Height - form.getPictureBox().Image.Height) / 2);

            int borderWidth = (form.Width - form.ClientSize.Width) /2;
            int titlebarHeight = form.Height - form.ClientSize.Height - 2 * borderWidth;

            return new Point(mouseLoc.X - (formLoc.X + borderWidth + frameLoc.X),
                mouseLoc.Y - (formLoc.Y + titlebarHeight + frameLoc.Y));
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        private static extern short GetAsyncKeyState(int keyCode);

        private static bool GetAsyncKeyState(Keys key)
        {
            short retVal = GetAsyncKeyState((int)key);

            //If the high-order bit is 1, the key is down. Otherwise, it is up.
            if ((retVal & 0x8000) == 0x8000)
            {
                return true;
            }

            return false;
        }
    }
}
